$(document).ready(function(){
	var MAX_TRIES = 100;
	//var cw = new Crossword("alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu zi omicron pi rho sigma tau upsilon phi chi psi omega".split(" "));
	//var words = "LIFETIME REGISTER HEAP STACK TEXT DATA IMPERATIVE FRAGMENTS JAVA BIND STRONGLYTYPED OVERLOAD PASSBYVALUE PASSBYREFERENCE ENCAPSULATION CLASS MEMBERS INSTANCE INITIALIZER INTERFACE METHOD INHERITANCE COMPOSITION POLYMORPHISM ADT VIRTUALFUNCTIONTABLE DYNAMICDISPATCH DELEGATE CLOSURE DECLARATIVE SCRIPT CONTAINER ITERATOR ROOTSET MARK RUNTIMESYSTEM RETAIN RELEASE TEMPLATE".split(" ");
	function showInput(){
		$('#stage-2').hide();
		$('#stage-1').show();		
	}
	
	function showCrossword(){
		$('#stage-1').hide();
		$('#stage-2').show();					
	}
	
	function removeDuplicatesFromWordCluePairs(words, clues){
    /*
		// remove duplicates
		var pairs = {};
		for(var i = 0; i < words.length; i++){
			pairs[words[i]] = clues[i];	
		}
		words.length = 0;
		clues.length = 0;
		for(var word in pairs){
			words.push(word);
			clues.push(pairs[word]);
		}		
        */
	}

    function breakStringIntoWordClue(line){
        var line = $.trim(line);
        var word = line.split(/\s+/)[0];
        var clue = $.trim(line.substr(word.length));
        return [word, clue];

    }
	
	function getWordsAndCluesFromTextbox(id, words, clues){
		var lines = $('#'+id).val().split("\n");
		for(var i = 0; i < lines.length; i++){
			//var data = $.trim(lines[i]).split(/\s(.+)?/);
            var data = breakStringIntoWordClue(lines[i]); 
			if(data.length < 2)	continue;
			data[0] = $.trim(data[0]);
			data[1] = $.trim(data[1]);
			if(data[0] == "" || data[1] == ""){
                continue;
            }
			words.push(data[0].toLowerCase());
			clues.push(data[1]);
		}
		removeDuplicatesFromWordCluePairs(words, clues);
	}
	
	function addLegendToPage(clues_id, groups){
		for(var k in groups){
			var html = [];
			for(var i = 0; i < groups[k].length; i++){
				html.push("<li><strong>" + groups[k][i]['position'] + ".</strong> " + groups[k][i]['clue'] + "</li>");
			}
			$('#'+clues_id+' .' + k).html(html.join("\n"));
		}		
		$('#'+clues_id).show();					
	}
	
	function makeTextboxContentPretty(){
		var words = [], clues = [];
		var lines = $('#crossword-data_vn').val().split("\n");
		for(var i = 0; i < lines.length; i++){
			//var data = $.trim(lines[i]).split(/\s(.+)?/);
            var data = breakStringIntoWordClue(lines[i]);
			data[0] = $.trim(data[0]);
			data[1] = $.trim(data[1]);
			if(data[0] == "" && data[1] == "") continue;
			words.push(data[0].toLowerCase());
			clues.push(data[1]);
		}			
		removeDuplicatesFromWordCluePairs(words, clues);
		// find longest word
		if(words.length == 0) return;
		var longest_word = words[0].length;
		if(longest_word == 0) return;		
		for(var i = 1; i < words.length; i++){
			if(words[i].length > longest_word) longest_word = words[i].length;	
		}
		
		var buffer = new Array(longest_word+1);
		var textbox_content = [];
		for(var i = 0; i < words.length; i++){
			for(var j = 0; j < buffer.length; j++) buffer[j] = " ";
			for(var j = 0; j < words[i].length; j++) buffer[j] = words[i].charAt(j);
			textbox_content.push(buffer.join(""), clues[i], "\n");
		}
		$('#crossword-data_vn').val(textbox_content.join(""));
		
		var words = [], clues = [];
		var lines = $('#crossword-data_en').val().split("\n");
		for(var i = 0; i < lines.length; i++){
			//var data = $.trim(lines[i]).split(/\s(.+)?/);
            var data = breakStringIntoWordClue(lines[i]);
			data[0] = $.trim(data[0]);
			data[1] = $.trim(data[1]);
			if(data[0] == "" && data[1] == "") continue;
			words.push(data[0].toLowerCase());
			clues.push(data[1]);
		}			
		removeDuplicatesFromWordCluePairs(words, clues);
		// find longest word
		if(words.length == 0) return;
		var longest_word = words[0].length;
		if(longest_word == 0) return;		
		for(var i = 1; i < words.length; i++){
			if(words[i].length > longest_word) longest_word = words[i].length;	
		}
		
		var buffer = new Array(longest_word+1);
		var textbox_content = [];
		for(var i = 0; i < words.length; i++){
			for(var j = 0; j < buffer.length; j++) buffer[j] = " ";
			for(var j = 0; j < words[i].length; j++) buffer[j] = words[i].charAt(j);
			textbox_content.push(buffer.join(""), clues[i], "\n");
		}
		$('#crossword-data_en').val(textbox_content.join(""));
	}
	function get_max_position(legend)
	{
		var across_offset = legend["across"].length - 1;
		var down_offset = legend["down"].length - 1;
//		console.log(legend["across"][across_offset]["position"]);
//		console.log(legend["down"][down_offset]["position"]);
		if(legend["across"][across_offset]["position"] > legend["down"][down_offset]["position"])
			return legend["across"][across_offset]["position"];
		else
			return legend["down"][down_offset]["position"];
	}
	$('#crossword-generate, #refresh').click(function(e){
		var is_fail = false;
		//vn
		var words = [], clues = [];
		getWordsAndCluesFromTextbox('crossword-data_vn',words, clues);
		makeTextboxContentPretty(words, clues);
//		console.log(words.length);
		// catch errors
		if(words.length < 2){
			alert("Your crossword needs at least two words!");
			return;
		} else if(words.length != clues.length){
			alert("Every word needs a clue!");
		}
		
		var gen_status = false;
		
		while(gen_status == false)
		{
			var cw = new Crossword(words, clues);
			var grid = cw.getSquareGrid(MAX_TRIES);		
			if(grid == null){
				gen_status = true;
				$('#crossword_vn, #clues_vn, #title_vn, #finish-up').hide();
				is_fail = true;
				if(cw){
					var bads = cw.getBadWords();
					var bad_words = [];
					for(var i = 0; i < bads.length; i++){
						bad_words.push(bads[i].word);
					}
					$('#bad-words_vn').text(bad_words.join(", "));
					$('.bad-words').show();
				} else {
					$('.bad-words').hide();	
				}
			} else {
				$('#title_vn').show().text($.trim($("#crossword-title_vn").val()) || "Untitled");
				$('#crossword_vn').show().html(CrosswordUtils.toHtml(grid, true));
				$('#finish-up').show();
				var legend = cw.getLegend(grid);
				addLegendToPage('clues_vn',legend);

				$('#grid_json_vn').val(JSON.stringify(grid, null));
				$('#legend_json_vn').val(JSON.stringify(legend, null));	
				$('#title_json_vn').val($("#crossword-title_vn").val());
				
//				console.log("words: "+words.length+" across: "+legend["across"].length+" down: "+legend["down"].length)
				if(words.length == get_max_position(legend))
				{
					gen_status = true;
				}
			}
		}
		
		
		//en
		var words = [], clues = [];
		getWordsAndCluesFromTextbox('crossword-data_en',words, clues);
		makeTextboxContentPretty(words, clues);
		
//		console.log(words.length);
		// catch errors
		if(words.length < 2){
			alert("Your crossword needs at least two words!");
			return;
		} else if(words.length != clues.length){
			alert("Every word needs a clue!");
		}
		
		var gen_status = false;
		
		while(gen_status == false)
		{
			var cw = new Crossword(words, clues);
			var grid = cw.getSquareGrid(MAX_TRIES);			
			if(grid == null){
				gen_status = true;
				$('#crossword_en, #clues_en, #title_en, #finish-up').hide();
				if(cw){
					var bads = cw.getBadWords();
					var bad_words = [];
					for(var i = 0; i < bads.length; i++){
						bad_words.push(bads[i].word);
					}
					$('#bad-words_en').text(bad_words.join(", "));
					$('.bad-words').show();
				} else {
					$('.bad-words').hide();	
				}
			} else {
				$('#title_en').show().text($.trim($("#crossword-title_en").val()) || "Untitled");
				$('#crossword_en').show().html(CrosswordUtils.toHtml(grid, true));
				$('#finish-up').show();
				var legend = cw.getLegend(grid)
				addLegendToPage('clues_en',legend);

				$('#grid_json_en').val(JSON.stringify(grid, null));
				$('#legend_json_en').val(JSON.stringify(legend, null));	
				$('#title_json_en').val($("#crossword-title_en").val());
//				console.log("words: "+words.length+" across: "+legend["across"].length+" down: "+legend["down"].length)
				if(words.length == get_max_position(legend))
				{
					gen_status = true;
				}
			}
		}
		
		if(is_fail) 
		{
			$('#fail').show(); 
			$('#div_vn').hide(); 
			$('#div_en').hide(); 
			$('#finish-up').hide(); 
		}
		else 
		{
			$('#fail').hide();
			$('#div_vn').show(); 
			$('#div_en').show(); 
			$('#finish-up').show(); 
		}
		showCrossword();
	});
	
	/*$('#example').click(function(){
		alert("hi");
	});*/
	
	$('#edit, #go-back').click(function(e){
		showInput();
	});	
	
	makeTextboxContentPretty();
	
	$('#example_vn').click(function(){
		var lines = $.trim($("#crossword-data_vn").val());
		lines += "\ndog Man's best friend \ncat Likes to chase mice\nbat Flying mammal\nelephant Has a trunk\nkangaroo Large marsupial";
		$('#crossword-data_vn').val($.trim(lines));
	});
	$('#example_en').click(function(){
		var lines = $.trim($("#crossword-data_en").val());
		lines += "\ndog Man's best friend \ncat Likes to chase mice\nbat Flying mammal\nelephant Has a trunk\nkangaroo Large marsupial";
		$('#crossword-data_en').val($.trim(lines));
	});
	
});
